package br.ufpe.cin.imlm2.jbeat.soot.throwableset.tags;

import java.util.*;

import soot.SootClass;
import soot.SootMethod;
import soot.tagkit.AttributeValueException;
import soot.tagkit.Tag;

public class TrapedSetTag implements Tag {

	public static final String TAG_NAME = "TrapedSetTag";

	private Map<SootClass, Set<SootMethod>> trappedMap;

	public TrapedSetTag() {
		trappedMap = new HashMap<SootClass, Set<SootMethod>>();
	}

	public void addTrapedException(SootClass exception, SootMethod source) {
		if (this.trappedMap.containsKey(exception)) {
			Set<SootMethod> sources = this.trappedMap.get(exception);
			sources.add(source);
		} else {
			Set<SootMethod> sources = new HashSet<SootMethod>();
			sources.add(source);
			this.trappedMap.put(exception, sources);
		}
	}

	public void addAllTrapedExceptions(Set<SootClass> exceptions,
			SootMethod source) {
		for (SootClass exception : exceptions) {
			this.addTrapedException(exception, source);
		}
	}

	public void removeTrapedException(SootClass exception) {
		this.trappedMap.remove(exception);
	}

	public Set<SootMethod> getTrapedSources(SootClass exception) {
		Set<SootMethod> sources = null;
		if (this.trappedMap.containsKey(exception))
			sources = new HashSet<SootMethod>(this.trappedMap.get(exception));
		return sources;
	}
	
	public Map<SootClass, Set<SootMethod>> getTrappedMap(){
		return this.trappedMap;
	}

	@Override
	public String getName() {
		return TAG_NAME;
	}

	@Override
	public byte[] getValue() throws AttributeValueException {
		return this.toString().getBytes();
	}

	@Override
	public String toString() {
		Iterator<SootClass> excepts = this.trappedMap.keySet().iterator();
		StringBuffer sb = new StringBuffer("{");
		while (excepts.hasNext()) {
			SootClass next = excepts.next();
			sb.append(next.getName() + ",");
		}
		if (sb.length() > 1)
			sb.deleteCharAt(sb.length() - 1);
		sb.append("}");
		return sb.toString();
	}

}
